package cn.wowjoy.pda.android_pharmacy.ui.activity.hospital.pill;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import cn.wowjoy.pda.android_pharmacy.R;
import cn.wowjoy.pda.android_pharmacy.common.core.BaseActivity;
import cn.wowjoy.pda.android_pharmacy.common.utils.Contants;
import cn.wowjoy.pda.android_pharmacy.common.utils.NetWorkUtils;
import cn.wowjoy.pda.android_pharmacy.common.utils.PreferenceManager;
import cn.wowjoy.pda.android_pharmacy.common.widget.CreateDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MyToast;
import cn.wowjoy.pda.android_pharmacy.databinding.ActivityInHospitalPillProgressBinding;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.inHospitalPatientInfo.InHospitalPillSingleBeen;
import cn.wowjoy.pda.android_pharmacy.mvvm.presenter.InHospitalPillProgressPresenter;
import cn.wowjoy.pda.android_pharmacy.mvvm.vm.InHospitalPillProgressViewModel;

public class InHospitalPillProgressActivity extends BaseActivity<ActivityInHospitalPillProgressBinding,InHospitalPillProgressViewModel,InHospitalPillProgressPresenter> implements View.OnClickListener, InHospitalPillProgressPresenter.OnSubmitHospitalResult {
    private boolean isResumed=false;
    private MDialog mDialog;
    private MDialog mFailDialog;
    //进度条分子
    private float countAlready;
    //当次药单 种类总数量
    private float TOTAL_NUM = Integer.parseInt(PreferenceManager.getInstance().getHospitalPillProgressTotal());
    //PDA扫码广播
    private ScanReceiver mScanReceiver;
    private IntentFilter intentFilter;
    public static final int UPDATE_PROGRESS_SUCCESS = 1;
    public static final int UPDATE_PROGRESS_FAIL = 2;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_PROGRESS_SUCCESS:
//                    binding.progressScanGet.incrementProgressBy(countAlready / TOTAL_NUM * 100);
                    if(null != mDialog){
                        CreateDialog.dismiss(InHospitalPillProgressActivity.this);
                        mDialog.cancel();
                    }

                    if (countAlready < TOTAL_NUM) {
                        countAlready++;
                    }
                    if (countAlready == TOTAL_NUM) {
                        //扫码完成
                        binding.rlScanImgv.setVisibility(View.GONE);
                        binding.rlVoice.setVisibility(View.VISIBLE);
                        binding.btCheckProgressSureSuccess.setVisibility(View.VISIBLE);
//                        binding.hospitalCheckTitle.titleBackLl.setVisibility(View.GONE);
                        binding.hospitalCheckTitle.titleMenuConfirm.setVisibility(View.GONE);
                        binding.progressScanGet.setProgress(100);
                        //检查是否所有都OK了
                        if (viewModel.checkTotal()) {
                            binding.btCheckProgressSureSuccess.setEnabled(true);
                            binding.btCheckProgressSureSuccess.setBackgroundColor(getResources().getColor(R.color.background_main));
                        }
                    }
                    updateFirstUI();
                    break;
                case UPDATE_PROGRESS_FAIL:
                    if(null != mFailDialog){
                        CreateDialog.dismiss(InHospitalPillProgressActivity.this);
                        mFailDialog.cancel();
                    }
                    break;
            }

        }
    };

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setPresenter(presenter);
        binding.setViewModel(viewModel);

        binding.hospitalCheckTitle.titleTextTv.setText("包药机审核");
        binding.hospitalCheckTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.hospitalCheckTitle.titleBackTv.setText("处方详情");
        binding.hospitalCheckTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        binding.hospitalCheckTitle.titleMenuConfirm.setText("手动复核");
        binding.hospitalCheckTitle.titleMenuConfirm.setTextColor(getResources().getColor(R.color.white));
        //TODO:PDA扫码广播的接收跳转
        mScanReceiver = new ScanReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Contants.WOW_NEW_ADD);

        updateFirstUI();
        binding.medicineIdScanGet.setText(presenter.DJJLID);
        binding.hospitalCheckTitle.titleBackLl.setOnClickListener(this);
        binding.btCheckProgressSureSuccess.setOnClickListener(this);
        binding.hospitalCheckTitle.titleMenuConfirm.setOnClickListener(this);
        presenter.registeOnSubmitResultListener(this);
        binding.imgv123.setOnClickListener(this);

    }

    /**
     *  根据唯一ID 查找是否存在
     * @param str
     */
    public void checkExist(String str) {
        InHospitalPillSingleBeen inHospitalPillSingleBeen = viewModel.checkExist(str);
        if( null == inHospitalPillSingleBeen){
            // 扫码错误
            CreateDialog.failDialog(InHospitalPillProgressActivity.this);
            return;
        }
        if(inHospitalPillSingleBeen.isCheck()){
            mFailDialog = CreateDialog.successDialog(InHospitalPillProgressActivity.this,6 ,"重复审核");
            mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS_FAIL,1000);
            return;
        }
        inHospitalPillSingleBeen.setCheck(true);
        mDialog = CreateDialog.successDialog(InHospitalPillProgressActivity.this,6 ,"复核成功");
        mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS_SUCCESS,600);

    }
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mScanReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CreateDialog.dismiss(InHospitalPillProgressActivity.this);
        if(null != mDialog){
            mDialog.cancel();
        }
        if(null != mFailDialog){
            mFailDialog.cancel();
        }
    }

    //TODO:界面药品信息的更新
    private void updateFirstUI() {
        countAlready=viewModel.calcNum();
        binding.tvProgressScanGet.setText((int)countAlready + "/" + (int)TOTAL_NUM);
        //设置进度条
        binding.progressScanGet.setProgress((int)((countAlready /TOTAL_NUM)*100));
        if (countAlready == TOTAL_NUM) {
            //8/8 BACK回去的
            binding.rlScanImgv.setVisibility(View.GONE);
            binding.rlVoice.setVisibility(View.VISIBLE);
            binding.btCheckProgressSureSuccess.setVisibility(View.VISIBLE);
//            binding.hospitalCheckTitle.titleBackLl.setVisibility(View.GONE);
            binding.hospitalCheckTitle.titleMenuConfirm.setVisibility(View.GONE);
            binding.progressScanGet.setProgress(100);
            //检查是否所有都OK了
            if (viewModel.checkTotal()) {
                binding.btCheckProgressSureSuccess.setEnabled(true);
                binding.btCheckProgressSureSuccess.setBackgroundColor(getResources().getColor(R.color.background_main));
            }
        }
    }

    @Override
    public void onBackPressed() {
        //药单未完成  BACK键返回  每次要把当前展示的加到集合中
        Intent intent = new Intent();
        intent.putExtra("currently", viewModel.mMoveBaens);
        setResult(Contants.REQUEST_BACK_CODE, intent);
        super.onBackPressed();
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_in_hospital_pill_progress;
    }

    @Override
    protected Class<InHospitalPillProgressPresenter> getPresenterClass() {
        return InHospitalPillProgressPresenter.class;
    }

    @Override
    protected Class<InHospitalPillProgressViewModel> getViewModelClass() {
        return InHospitalPillProgressViewModel.class;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_back_ll:
                //BACK 键
                Intent intent = new Intent();
                intent.putExtra("currently", viewModel.mMoveBaens);
                setResult(Contants.REQUEST_BACK_CODE, intent);
                finish();
                break;
            case R.id.bt_check_progress_sure_success:
                //检查   更新住院取完药接口
                if(NetWorkUtils.isWifi(InHospitalPillProgressActivity.this)){
                    presenter.update("1",PreferenceManager.getInstance().getLUserId());
                }else{
                    CreateDialog.failDialog3(InHospitalPillProgressActivity.this,"错误","当前网络不可用，请检查你的网络设置");
                }
                break;
            case R.id.title_menu_confirm:
                //跳转至手动审核
                Intent intent2 = new Intent(InHospitalPillProgressActivity.this, InHospitalPillHandActivity.class);
//                intent2.putExtra("total", viewModel.FirstTotal);
                startActivityForResult(intent2,Contants.REQUEST_CODE);
                break;
            case R.id.imgv123:
                //测试  模拟扫码枪
//                checkExist(mStrings.remove(0));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case Contants.REQUEST_CODE:
                //手动审核的结果
                switch (resultCode){
                    case Contants.RESULT_HAND_SUCCESS_CODE:
                        String check = data.getExtras().getString("hand");
//                        Log.e("TAG", "onActivityResult: "+check.toString() );
                        checkExist(check);
                        //手动审核的药 有并且还没被核对过
//                        if(viewModel.checkSecond(check)){
//                            mDialog = CreateDialog.successDialog(InHospitalPillProgressActivity.this, 6 ,"审核成功");
//                            mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS_SUCCESS,600);
//                            return;
//                        }
//                        //手动审核的药 有但是已经被核对过了
//                        CreateDialog.failDialog2(InHospitalPillProgressActivity.this);
                        break;
                    case Contants.RESULT_HAND_FAIL_CODE:

                        break;
                }
                break;
        }
    }

    //药单更新成功
    @Override
    public void submitSuccess() {
        new MyToast(this).showinfo("审核成功");
        startActivity(new Intent(InHospitalPillProgressActivity.this, InHospitalPillIndexActivity.class));
    }
    //药单更新失败
    @Override
    public void submitFail(String errMsg) {
        new MyToast(this).showinfo(errMsg);
        startActivity(new Intent(InHospitalPillProgressActivity.this, InHospitalPillIndexActivity.class));
    }
    //TODO:接收PDA扫码广播，准备跳转
    class ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case Contants.WOW_NEW_ADD:
                    String stringExtra = intent.getStringExtra(Contants.WOW_NEW_KEY);
//                    new MyToast(InHospitalCheckResultActivity.this).showinfo("扫到的是: "+stringExtra);
                    checkExist(stringExtra);
                    break;
            }
        }
    }
}
